import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_juwo/common/common_index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_juwo/ui/custom/real_rich_text.dart';
import 'package:flutter_juwo/ui/custom/task_tips_dialog.dart';
import 'package:flutter_juwo/ui/model/base_entity.dart';
import 'package:flutter_juwo/ui/utils/toast_utils.dart';
import 'package:flutter_juwo/ui/utils/utils.dart';

import 'model/detail_entity.dart';

class TaskDetail extends StatefulWidget {
  String id = "";

  TaskDetail(this.id);

  @override
  _TaskDetailState createState() => _TaskDetailState();
}

class _TaskDetailState extends State<TaskDetail> {
  MyPageState ps = MyPageState.LOADING;
  DetailEntity _entity;
  DetailDataAccountlist account;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this.getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: appBar(context, "任务详情"),
      body: getBody(),
    );
  }

  getBody() {
    if (ps == MyPageState.LOADING) {
      return LoadingPage();
    }

    if (ps == MyPageState.HAVE_DATA) {
      return Column(
        children: <Widget>[
          UiUtils.divider(height: 2),
          Expanded(
            flex: 1,
            child: ListView(
              children: <Widget>[
                UiUtils.divider(height: 2),

                ///顶部文字说明
                getRow1(_entity.data),
                getRow2(_entity.data),
                getRow3(_entity.data),
                //线
                getRow4(),
                //商家说明
                getRow5(_entity.data.description),

                //固定说明
                getRow6(),

                //线
                getRow7(),

                //任务步骤
                getRow8(),
                //线
                getRow4(),
                getRow9(_entity.data.motion)
                //  getRow5()
              ],
            ),
          ),
          getBottom()
        ],
      );
    }
  }

  void getData() {
    FormData formData = FormData.from({"id": widget.id});

    DioManager.getInstance().post(Api.TASK_TASKDETAIL, formData, (json) {
      _entity = DetailEntity.fromJson(json);
      if (null == _entity) {
        ToastUtil.showShortErrToast(Api.ERR_NOTHING);
        NavigatorUtils.goBack(context);
        return;
      }
      if (_entity.code != 200) {
        ToastUtil.showShortErrToast(_entity.message);
        NavigatorUtils.goBack(context);
        return;
      }

      ps = MyPageState.HAVE_DATA;
      setState(() {});
    }, (err) {
      print("请求失败$err");
      ToastUtil.showShortErrToast(Api.ERR_NOTHING);
      NavigatorUtils.goBack(context);
    });
  }

  Widget appBar(BuildContext context, String title) {
    return AppBar(
      brightness: Brightness.light,
      backgroundColor: Colours.white,
      title: Text(
        '$title',
        style: TextStyle(
            fontSize: ScreenUtil().setSp(34),
            fontFamily: Font.PingFangBlod,
            color: Colours.appC1),
      ),
      centerTitle: true,
      elevation: 0.0,
      leading: InkWell(
          highlightColor: Color(0xFFB3E5FC),
          onTap: () {
            Navigator.pop(context);
          },
          child: Container(
            padding: EdgeInsets.fromLTRB(12.0, 0.0, 12.0, 0.0),
            child: Image.asset(
              Utils.getImgPath('return_left'),
              width: 18.0,
              height: 20.0,
            ),
          )),
      actions: <Widget>[
        InkWell(
          onTap: () {
            showMyDialog();
          },
          child: Container(
            padding: EdgeInsets.all(ScreenUtil().setWidth(30)),
            alignment: Alignment.center,
            child: Text(
              account == null ? "请选择账号" : account.text,
              style: TextStyles.custom(
                  28, Colours.appC16, Font.PingFangRegular),
            ),
          ),
        )
      ],
    );
  }

  getBottom() {
    return Container(
      padding: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(10),
          ScreenUtil().setWidth(10),
          ScreenUtil().setWidth(10),
          ScreenUtil().setWidth(30)),
      child: UiUtils.bottomBotton("立即申请", () {
        if (account == null) {
          ToastUtil.showShortErrToast("请选择账号！");
          return;
        }
        //提示
        showTipDialog(context);

        //提交
        upData();
      }),
    );
  }

  getRow1(DetailData data) {
    return Container(
      margin: EdgeInsets.all(ScreenUtil().setWidth(30)),
      child: Row(
        children: <Widget>[
          ClipRRect(
            borderRadius: BorderRadius.circular(6),
            child: UiUtils.cachedNetworkImage(40, 40, data.platformpic),
          ),
          Expanded(
              flex: 1,
              child: Container(
                margin: EdgeInsets.only(left: ScreenUtil().setWidth(10)),
                child: Text(data.name,
                    style: TextStyles.custom(
                        28, Colours.appC2, Font.PingFangMedium)),
              )),
          Container(
            padding: EdgeInsets.fromLTRB(
                ScreenUtil().setWidth(5), 0, ScreenUtil().setWidth(5), 0),
            decoration:
                BoxDecoration(border: Border.all(color: Colours.appC10)),
            child: Text(data.timeCn,
                style: TextStyles.custom(
                    28, Colours.appC10, Font.PingFangMedium)),
          ),
          Container(
            margin: EdgeInsets.only(left: ScreenUtil().setWidth(10)),
            padding: EdgeInsets.fromLTRB(
                ScreenUtil().setWidth(5), 0, ScreenUtil().setWidth(5), 0),
            decoration:
                BoxDecoration(border: Border.all(color: Colours.appC095105239)),
            child: Text(data.categoryname == "电商任务" ? "垫付" : "浏览",
                style: TextStyles.custom(
                    28, Colours.appC095105239, Font.PingFangMedium)),
          )
        ],
      ),
    );
  }

  getRow2(DetailData data) {
    return Container(
      margin: EdgeInsets.only(
          left: ScreenUtil().setWidth(30), right: ScreenUtil().setWidth(30)),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: <Widget>[
          RealRichText([
            TextSpan(
              text: "${data.price}金",
              style: TextStyles.custom(
                  40, Colours.appC16, Font.PingFangBlod),
            ),
            TextSpan(
              text: "  预付金额:${data.priceGoods}元",
              style: TextStyles.custom(
                  26, Colours.appC2, Font.PingFangMedium),
            )
          ]),
        ],
      ),
    );
  }

  getRow3(DetailData data) {
    return Container(
      margin: EdgeInsets.only(
          left: ScreenUtil().setWidth(30),
          right: ScreenUtil().setWidth(30),
          top: ScreenUtil().setWidth(26)),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: <Widget>[
          RealRichText([
            TextSpan(
              text: "截止时间：",
              style: TextStyles.custom(
                  26, Colours.appC3, Font.PingFangRegular),
            ),
            TextSpan(
              text: "  ${data.deaddate}",
              style: TextStyles.custom(
                  26, Colours.appC3, Font.PingFangRegular),
            )
          ]),
          Expanded(
            flex: 1,
            child: Container(
              alignment: Alignment.centerRight,
              child: Text(
                "剩余${data.stockNum}次",
                style: TextStyles.custom(
                    26, Colours.appC3, Font.PingFangRegular),
              ),
            ),
          )
        ],
      ),
    );
  }

  getRow4() {
    return Container(
      margin: EdgeInsets.all(ScreenUtil().setWidth(30)),
      child: UiUtils.divider(height: 1.5),
    );
  }

  getRow5(String description) {
    return Container(
      margin: EdgeInsets.fromLTRB(ScreenUtil().setWidth(30), 0,
          ScreenUtil().setWidth(30), ScreenUtil().setWidth(30)),
      child: Text(description,
          style: TextStyles.custom(
              28, Colours.appC2, Font.PingFangRegular)),
    );
  }

  getRow6() {
    return Container(
      margin: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(0),
          ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(30)),
      padding: EdgeInsets.all(ScreenUtil().setWidth(10)),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(6), color: Color(0xFFffdedf)),
      child: Text(
        "1. 如商家无特别说明，不得使用淘客等返利工具\n2. 与商家客服聊天过程中，不得提及【刷单】【补单】【巨沃】等敏感字眼，违者直接封禁账号\n3. 接单提示：如果订单为当日订单，请在接单后1小时内完成订单支付（不含预约时间）；如订单为多日订单，请在接单后2小时内完成订单支付（不含预约时间）；否则系统将自动取消，并且扣除2金币\n4. 请使用已选择账号接单，如无法完成订单，请在接单后10分钟内取消（不扣金币）",
        style: TextStyles.custom(
            28, Color(0xFFdf3033), Font.PingFangRegular),
      ),
    );
  }

  getRow7() {
    return Container(
      child: UiUtils.divider(height: 10),
    );
  }

  getRow8() {
    return Container(
      margin: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(30), ScreenUtil().setWidth(30), 0, 0),
      child: Row(
        children: <Widget>[
          Container(
            color: Colours.appC16,
            width: ScreenUtil().setWidth(8),
            height: ScreenUtil().setWidth(35),
          ),
          Container(
            margin: EdgeInsets.only(left: ScreenUtil().setWidth(30)),
            child: Text(
              "任务步骤",
              style: TextStyles.custom(
                  28, Colours.appC1, Font.PingFangMedium),
            ),
          ),
        ],
      ),
    );
  }

  getRow9(List<String> motion) {
    List<Widget> list = [];
    for (int i = 0; i < motion.length; i++) {
      list.add(getItem(i + 1, motion[i]));
    }

    return Container(
      margin: EdgeInsets.only(
          left: ScreenUtil().setWidth(30), right: ScreenUtil().setWidth(30)),
      child: Wrap(
        spacing: 2, //主轴上子控件的间距
        runSpacing: 5, //交叉轴上子控件之间的间距
        children: list, //要显示的子控件集合
      ),
    );
  }

  Widget getItem(int num, String motion) {
    return Container(
      child: Chip(
        backgroundColor: Colors.white,
        avatar: Container(
          alignment: Alignment.center,
          width: ScreenUtil().setWidth(40),
          height: ScreenUtil().setWidth(40),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(16),
              border: Border.all(color: Colors.red)),
          child: Text(
            '$num',
            style:
                TextStyles.custom(28, Colors.red, Font.PingFangMedium),
          ),
        ),
        label: Text(
          '$motion',
          style: TextStyles.custom(
              28, Colours.appC1, Font.PingFangMedium),
        ),
      ),
    );
  }

  void showMyDialog() {
    List<Widget> widgets = [];
    widgets.add(
      Container(
        height: ScreenUtil().setWidth(78),
        child: Text(
          "选择电商账号",
          style:
              TextStyles.custom(30, Colours.appC1, Font.PingFangBlod),
        ),
      ),
    );
    for (int i = 0; i < _entity.data.accountList.length; i++) {
      widgets.add(UiUtils.divider());
      widgets.add(InkWell(
        onTap: () {
          account = _entity.data.accountList[i];
          setState(() {});
          NavigatorUtils.goBack(context);
        },
        child: Container(
          height: ScreenUtil().setWidth(90),
          alignment: Alignment.center,
          child: Text(
            "${_entity.data.accountList[i].text}",
            style: TextStyles.custom(
                28, Colours.appC16, Font.PingFangMedium),
          ),
        ),
      ));
    }

    showElasticDialog(
        context: context,
        builder: (BuildContext context) {
          return Material(
            type: MaterialType.transparency,
            child: Center(
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(8.0),
                ),
                width: ScreenUtil().setWidth(540),
                height: ScreenUtil().setWidth(
                    48 + 78 + (90 + 1.0) * _entity.data.accountList.length),
                padding: EdgeInsets.only(top: ScreenUtil().setWidth(48)),
                child: Theme(
                  data: ThemeData(
                    buttonTheme: ButtonThemeData(
                      minWidth: double.infinity,
                    ),
                    textTheme: TextTheme(
                        button: TextStyle(
                      fontSize: Dimens.font_sp14,
                    )),
                  ),
                  child: Column(
                    children: widgets,
                  ),
                ),
              ),
            ),
          );
        });
  }

  ///立即申请
  void upData() {}

  //提示 确定接单
  void showTipDialog(BuildContext thisContext) {
    ///显示Dialog
    showElasticDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return TaskTipsDialog(
            taskType: _entity.data.categoryname,
            orderType: "${_entity.data.timeCn}单",
            timeLimit: _entity.data.timeCn == "当日"
                ? "1小时（完成支付，不含等待时间）"
                : "2小时（完成支付，不含等待时间）",
            onPressed: () {
              //提交数据
              FormData params = FormData.from(
                  {"id": _entity.data.id, "account_id": account.value});
              DioManager.getInstance().post(Api.TASK_APPLYTASK, params, (json) {
                print(json);

                BaseEntity entity = BaseEntity.fromJson(json);
                if (null == entity) {
                  ToastUtil.showShortErrToast(Api.ERR_NOTHING);
                }

                if (entity.code != 200) {
                  ToastUtil.showShortErrToast(entity.message);
                }

                ///跳转到进行任务页面
                NavigatorUtils.push(
                    thisContext, "${Routes.taskStep}?id=${widget.id}",
                    replace: true);

              /*  try {


                } catch (e) {
                  print("确认接单：${e.toString()}");
                  ToastUtil.showShortErrToast(e.toString());
                }*/

                //成功进去任务列表
              }, (err) {
                ToastUtil.showShortErrToast(Api.ERR_TIME_OUT);
              });
            },
          );
        });
  }
}
